import React, { PureComponent } from 'react'
import { DatePicker } from 'antd'
import moment from 'moment'

class UdYearPicker extends PureComponent<any, IUdYearPickerState> {
  constructor(props: any) {
    super(props)
    this.state = {
      values: null,
      open: false,
    }
  }

  componentDidMount() {
    this.handleProps(this.props)
  }

  componentWillReceiveProps(nextProps: Readonly<any>) {
    this.handleProps(nextProps)
  }

  private handleProps = (props: any) => {
    if (props.value && props.value !== '') {
      this.setState({ values: moment(props.value) })
    } else {
      this.setState({ values: null })
    }
  }

  handleOpenChange = status => {
    if (status) {
      this.setState({ open: true })
    } else {
      this.setState({ open: false })
    }
  }

  handlePanelChange = value => {
    let format = 'YYYY'
    this.props.onChange(value ? value.format(format) : null)
    this.setState({
      open: false,
    })
  }

  clearValue = () => {
    this.setState({
      values: null,
      open: false,
    })
    this.props.onChange(null)
  }

  render() {
    let values: any = {}
    if (this.state.values != null) {
      values.value = this.state.values
    }
    return (
      <DatePicker
        {...this.props}
        mode="year"
        placeholder="请选择年份"
        format="YYYY"
        onOpenChange={this.handleOpenChange}
        onPanelChange={this.handlePanelChange}
        onChange={this.clearValue}
        open={this.state.open}
        style={{width:'100%'}}
        {...values}
      />
    )
  }
}
interface IUdYearPickerProps {}
interface IUdYearPickerState {
  values?: any
  open: boolean
}
export default UdYearPicker
